package gpslmall

import (
    "errors"
    "encoding/json"
	//"thirdpaysdk/utils/mapstruct"
	"github.com/astaxie/beego"
)

type RequestPayReq struct {
	MerchantOrderNo	  string `json:"merchantOrderNo"`   //商户订单号
	ActualPrice       string `json:"actualPrice"`       //实付金额(单位:元)
	ProductName	      string `json:"productName"`       //产品名称
	PayType	          string `json:"payType"`     //支付类型小程序(WEIXIN_XCX) 
	OpenId	          string `json:"openId"`            //微信用户openId
	AppId	          string `json:"appId"`             //微信appId
	MerchantNotifyUrl string `json:"merchantNotifyUrl"` //支付成功回调地址
}

type RequestPayRsp struct {
	*BaseRsp
	Content	string	`json:"content"`   //
}

type Content struct {
	OrderNo	      string   `json:"orderNo"`   //
	PayAmount     string   `json:"payAmount"` //
	PayType	      string   `json:"payType"`   //
	RequestDesc   string   `json:"requestDesc"`   //
	TransactionNo string   `json:"transactionNo"`	   // 
    ResultStr     string   `json:"resultMsg"` //
}

type ResultMsg struct {
	AppId	  string `json:"appId"`	    //
    TimeStamp string `json:"timeStamp"` //
    NonceStr  string `json:"nonceStr"`  //
    Package	  string `json:"package"`   //
    SignType  string `json:"signType"`  //
    PaySign   string `json:"paySign"`   //
}

func MicroAppPay(shopKey,secrecode,appId,orderId,price,openId,notifyUrl,productName string)(payInfo *ResultMsg, err error){
	method := "buyer.requestPay"
	req := new(RequestPayReq)
	req.MerchantOrderNo = orderId
	req.ActualPrice = price
	req.ProductName = productName
	req.PayType = "WEIXIN_XCX"
	req.OpenId = openId
	req.AppId = appId
	req.MerchantNotifyUrl = notifyUrl
	reqURL := "http://106.75.191.107/m.api"
	//reqURL := "http://openapi.oceanz.cn/m.api"
	sdk := NewSDK(reqURL, shopKey, secrecode)
	rsp := new(RequestPayRsp)
	_, err = sdk.Request(method, req, rsp)
	if err != nil {
		beego.Debug("Gpslmall MicroAppPay err:", err.Error())
		return
	}
	if rsp.ReturnCode != "00000000" {
	   err = errors.New(rsp.ErrorMsg)
	}
	payContent := new(Content)
	err = json.Unmarshal([]byte(rsp.Content), payContent)
	if err != nil {
	    return
	}
	payInfo = new(ResultMsg)
	err = json.Unmarshal([]byte(payContent.ResultStr), payInfo)
	if err != nil {
	    return
	}
	return
}
